﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Tunnel.Tools.FcmsTools
{
    public class FcmsProtocol
    {
        /// <summary>
        /// 将播放列表的byte列表版本转换成发送文件的指令
        /// </summary>
        /// <param name="playList">播放列表的byte列表版本</param>
        /// <param name="fileName">发送的文件名</param>
        /// <returns>发送文件的指令列表</returns>
        public List<List<byte>> GetCommandsList(List<byte> playList, string fileName)
        {
            List<List<byte>> commandList = new List<List<byte>>(); //转化播放列表文件为发送指令


            List<byte> fileNameList = Encoding.ASCII.GetBytes(fileName).ToList();
            uint offset = 0;   //播放列表超过2048(也就是0x800)字节时的偏移量
            bool needMoreSegmentFlag = true;

            while (needMoreSegmentFlag)
            {
                List<byte> commandByte = new List<byte>();
                commandByte.Add(0x02);  //帧头02
                commandByte.Add(0x30);  //目标地址00，第一个0
                commandByte.Add(0x30);  //目标地址00，第二个0
                commandByte.Add(0x31);  //协议类型10，第一个1
                commandByte.Add(0x30);  //协议类型10，第二个0
                commandByte.AddRange(fileNameList);  //文件名
                commandByte.Add(0x2B);  //分隔符
                commandByte.AddRange(GetOffset(offset)); //偏移量
                List<byte> fileSegment = new List<byte>();
                needMoreSegmentFlag = GetFileSegment(ref playList, out fileSegment);
                commandByte.AddRange(fileSegment);  //文件片段
                if (!GetCRC(ref commandByte))
                {
                    return new List<List<byte>>();//增加CRC校验,CRC校验失败，则返回一个空指令列表
                }
                if(!EscapeString(ref commandByte, 5))
                {
                    return new List<List<byte>>();//进行字符转义,如果字符转义失败，则返回一个空指令列表
                }                
                commandByte.Add(0x03); //帧尾03
                offset += 0x800;  //偏移量增加2048
                commandList.Add(commandByte);
            }

            return commandList;
        }

        /// <summary>
        /// 通过网络向情报板异步发送文件
        /// </summary>
        /// <param name="fileName">要发送的文件名，可以包含路径</param>
        /// <param name="playList">要发送的播放列表的byte列表版本</param>
        /// <param name="fcmsId">情报板设备ID</param>
        /// <param name="ipAddress">情报板的IP地址</param>
        /// <param name="port">情报板的端口号</param>
        public async Task<bool> UploadFileByNetAsync(string fileName, List<byte> playList, string fcmsId, IPAddress ipAddress, int port)
        {
            List<List<byte>> commandsList = GetCommandsList(playList, fileName);
            byte[] buffer;
            bool successFlag = false;
            try
            {
                using (TcpClient tcpClient = new TcpClient())
                {
                    await tcpClient.ConnectAsync(ipAddress, port);
                    using (NetworkStream networkStream = tcpClient.GetStream())
                    {
                        networkStream.ReadTimeout = Properties.Settings.Default.NetworkTimeOut * 1000;
                        foreach (var command in commandsList)
                        {
                            await networkStream.WriteAsync(command.ToArray(), 0, command.Count);                            
                            buffer = new byte[tcpClient.ReceiveBufferSize];
                            await Task.Run(() =>
                            {
                                networkStream.ReadAsync(buffer, 0, buffer.Length).Wait(networkStream.ReadTimeout);
                            });
                            try
                            {
                                successFlag = (buffer[3] == 0x30) ? true : false;
                            }
                            catch
                            {
                                successFlag = false;
                            }
                        }
                        return successFlag;
                    }
                }
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 通过网络向情报板同步发送文件（阻塞）
        /// </summary>
        /// <param name="fileName">要发送的文件名，可以包含路径</param>
        /// <param name="playList">要发送的播放列表的byte列表版本</param>
        /// <param name="fcmsId">情报板设备ID</param>
        /// <param name="ipAddress">情报板的IP地址</param>
        /// <param name="port">情报板的端口号</param>
        public bool UploadFileByNet(string fileName, List<byte> playList, string fcmsId, IPAddress ipAddress, int port)
        {
            List<List<byte>> commandsList = GetCommandsList(playList, fileName);
            byte[] buffer;
            bool successFlag = false;
            try
            {
                using (TcpClient tcpClient = new TcpClient())
                {
                    tcpClient.Connect(ipAddress, port);
                    using (NetworkStream networkStream = tcpClient.GetStream())
                    {
                        networkStream.ReadTimeout = Properties.Settings.Default.NetworkTimeOut * 1000;
                        foreach (var command in commandsList)
                        {
                            networkStream.Write(command.ToArray(), 0, command.Count);
                            buffer = new byte[tcpClient.ReceiveBufferSize];
                            networkStream.ReadAsync(buffer, 0, buffer.Length).Wait(networkStream.ReadTimeout);
                            
                            try
                            {
                                successFlag = (buffer[3] == 0x30) ? true : false;
                            }
                            catch
                            {
                                successFlag = false;
                            }
                        }
                        return successFlag;
                    }
                }
            }
            catch
            {
                return false;
            }
        }


        /// <summary>
        /// 通过串口向情报板异步发送文件
        /// </summary>
        /// <param name="fileName">要发送的文件名，可以包含路径</param>
        /// <param name="playList">要发送的播放列表的byte列表版本</param>
        /// <param name="fcmsId">情报板设备ID</param>
        /// <param name="portName">情报板的端口号</param>
        public async Task<bool> UploadFileBySpAsync(string fileName, List<byte> playList, string fcmsId, string portName)
        {
            List<List<byte>> commandsList = GetCommandsList(playList, fileName);
            bool successFlag = false;
            SerialPort serialPort = new SerialPort
            {
                PortName = portName,
                BaudRate = 9600,
                Parity = 0,
                DataBits = 8,
                StopBits = StopBits.One,
                ReadBufferSize = 16384,
                ReadTimeout = Properties.Settings.Default.SerialPortTimeOut * 1000
            };   //初始化串口
            try
            {
                serialPort.Open();  //打开串口
                byte[] result; //用以记录情报板向上位机回复的指令
                foreach (var command in commandsList)
                {
                    await Task.Factory.StartNew(new Action(() => { serialPort.Write(command.ToArray(), 0, command.Count); }));

                    result = await Task.Factory.StartNew<byte[]>(new Func<byte[]>(() =>
                      {
                          Task.Delay(Properties.Settings.Default.SerialPortTimeOut * 1000).Wait();
                          byte[] buffer = new byte[serialPort.BytesToRead];
                          serialPort.Read(buffer, 0, buffer.Length);
                          return buffer;
                      }));
                    try
                    {
                        successFlag = (result[3] == 0x30) ? true : false;
                    }
                    catch
                    {
                        successFlag = false;
                    }
                }
                serialPort.Close();
            }
            catch
            {
                return false;
            }
            return successFlag;

        }
        /// <summary>
        /// 通过串口向情报板同步发送文件（阻塞）
        /// </summary>
        /// <param name="fileName">要发送的文件名，可以包含路径</param>
        /// <param name="playList">要发送的播放列表的byte列表版本</param>
        /// <param name="fcmsId">情报板设备ID</param>
        /// <param name="portName">情报板的端口号</param>
        public bool UploadFileBySp(string fileName, List<byte> playList, string fcmsId, string portName)
        {
            List<List<byte>> commandsList = GetCommandsList(playList, fileName);
            bool successFlag = false;
            SerialPort serialPort = new SerialPort
            {
                PortName = portName,
                BaudRate = 9600,
                Parity = 0,
                DataBits = 8,
                StopBits = StopBits.One,
                ReadBufferSize = 16384,
                ReadTimeout = Properties.Settings.Default.SerialPortTimeOut * 1000
            };   //初始化串口
            try
            {
                serialPort.Open();  //打开串口
                byte[] result; //用以记录情报板向上位机回复的指令
                foreach (var command in commandsList)
                {
                    serialPort.Write(command.ToArray(), 0, command.Count); 

                    Task.Delay(Properties.Settings.Default.SerialPortTimeOut * 1000).Wait();
                    byte[] buffer = new byte[serialPort.BytesToRead];
                    serialPort.Read(buffer, 0, buffer.Length);
                    result = buffer;
                    try
                    {
                        successFlag = (result[3] == 0x30) ? true : false;
                    }
                    catch
                    {
                        successFlag = false;
                    }
                }
                serialPort.Close();
            }
            catch
            {
                return false;
            }            
            return successFlag;

        }



        /// <summary>
        /// 利用数据库向情报板异步发送文件
        /// </summary>
        /// <param name="fileName">要发送的文件名，可以包含路径</param>
        /// <param name="playList">要发送的播放列表的byte列表版本</param>
        /// <param name="fcmsId">情报板的设备ID</param>
        /// <param name="paramName">情报板的PLC变量名</param>
        /// <param name="controlSwitch">PLC的ControlSwitch变量名</param>
        public async Task<bool> UploadFileBySqlAsync(string fileName, List<byte> playList, string fcmsId, string paramName, string controlSwitch)
        {
            List<List<byte>> commandList = GetCommandsList(playList, fileName);

            DBHelper dh = new DBHelper();
            List<SqlCommand> commands = new List<SqlCommand>();
            SqlCommand openSwitchSql = new SqlCommand();


            openSwitchSql.CommandText = "INSERT INTO R_Command([CommandID],[DeviceID],[ParamName],[ParamValue],[UpdateTime],[UpdateBy],[Runned]) VALUES(@commandid,@deviceid,@paramname,@paramvalue,GETDATE(),@updateby,'0')";
            openSwitchSql.Parameters.Add(new SqlParameter("@commandid", DBHelper.GetGuid));
            openSwitchSql.Parameters.Add(new SqlParameter("@deviceid", fcmsId));
            openSwitchSql.Parameters.Add(new SqlParameter("@paramname", controlSwitch));
            openSwitchSql.Parameters.Add(new SqlParameter("@paramvalue", "1"));
            openSwitchSql.Parameters.Add(new SqlParameter("@updateby", Global.UserID));
            commands.Add(openSwitchSql);

            foreach (var item in commandList)
            {
                SqlCommand FcmsCommand = new SqlCommand();
                FcmsCommand.CommandText = "INSERT INTO R_Command([CommandID],[DeviceID],[ParamName],[ParamValue],[UpdateTime],[UpdateBy],[Runned]) VALUES(@commandid,@deviceid,@paramname,@paramvalue,GETDATE(),@updateby,'0')";
                FcmsCommand.Parameters.Add(new SqlParameter("@commandid", DBHelper.GetGuid));
                FcmsCommand.Parameters.Add(new SqlParameter("@deviceid", fcmsId));
                FcmsCommand.Parameters.Add(new SqlParameter("@paramname", paramName));
                FcmsCommand.Parameters.Add(new SqlParameter("@paramvalue", GetCommandString(item)));
                FcmsCommand.Parameters.Add(new SqlParameter("@updateby", Global.UserID));
                commands.Add(FcmsCommand);
            }

            int count = await dh.RunTransactionCommandsAsync(commands);

            await Task.Delay(Properties.Settings.Default.ControlSwitchCloseTime*1000);//经过一定秒数后关闭PLC的ControlSwitch
            SqlCommand closeSwitchSql = new SqlCommand();
            closeSwitchSql.CommandText = "INSERT INTO R_Command([CommandID],[DeviceID],[ParamName],[ParamValue],[UpdateTime],[UpdateBy],[Runned]) VALUES(@commandid,@deviceid,@paramname,@paramvalue,GETDATE(),@updateby,'0')";
            closeSwitchSql.Parameters.Add(new SqlParameter("@commandid", DBHelper.GetGuid));
            closeSwitchSql.Parameters.Add(new SqlParameter("@deviceid", fcmsId));
            closeSwitchSql.Parameters.Add(new SqlParameter("@paramname", controlSwitch));
            closeSwitchSql.Parameters.Add(new SqlParameter("@paramvalue", "0"));
            closeSwitchSql.Parameters.Add(new SqlParameter("@updateby", Global.UserID));

            await dh.RunCommandAsync(closeSwitchSql);

            return count > 0;


        }
        /// <summary>
        /// 利用数据库向情报板同步发送文件
        /// </summary>
        /// <param name="fileName">要发送的文件名，可以包含路径</param>
        /// <param name="playList">要发送的播放列表的byte列表版本</param>
        /// <param name="fcmsId">情报板的设备ID</param>
        /// <param name="paramName">情报板的PLC变量名</param>
        /// <param name="controlSwitch">PLC的ControlSwitch变量名</param>
        public bool UploadFileBySql(string fileName, List<byte> playList, string fcmsId, string paramName, string controlSwitch)
        {
            List<List<byte>> commandList = GetCommandsList(playList, fileName);

            DBHelper dh = new DBHelper();
            List<SqlCommand> commands = new List<SqlCommand>();
            SqlCommand openSwitchSql = new SqlCommand();


            openSwitchSql.CommandText = "INSERT INTO R_Command([CommandID],[DeviceID],[ParamName],[ParamValue],[UpdateTime],[UpdateBy],[Runned]) VALUES(@commandid,@deviceid,@paramname,@paramvalue,GETDATE(),@updateby,'0')";
            openSwitchSql.Parameters.Add(new SqlParameter("@commandid", DBHelper.GetGuid));
            openSwitchSql.Parameters.Add(new SqlParameter("@deviceid", fcmsId));
            openSwitchSql.Parameters.Add(new SqlParameter("@paramname", controlSwitch));
            openSwitchSql.Parameters.Add(new SqlParameter("@paramvalue", "1"));
            openSwitchSql.Parameters.Add(new SqlParameter("@updateby", Global.UserID));
            commands.Add(openSwitchSql);

            foreach (var item in commandList)
            {
                SqlCommand FcmsCommand = new SqlCommand();
                FcmsCommand.CommandText = "INSERT INTO R_Command([CommandID],[DeviceID],[ParamName],[ParamValue],[UpdateTime],[UpdateBy],[Runned]) VALUES(@commandid,@deviceid,@paramname,@paramvalue,GETDATE(),@updateby,'0')";
                FcmsCommand.Parameters.Add(new SqlParameter("@commandid", DBHelper.GetGuid));
                FcmsCommand.Parameters.Add(new SqlParameter("@deviceid", fcmsId));
                FcmsCommand.Parameters.Add(new SqlParameter("@paramname", paramName));
                FcmsCommand.Parameters.Add(new SqlParameter("@paramvalue", GetCommandString(item)));
                FcmsCommand.Parameters.Add(new SqlParameter("@updateby", Global.UserID));
                commands.Add(FcmsCommand);
            }

            int count = dh.RunTransactionCommands(commands);

            Task.Delay(Properties.Settings.Default.ControlSwitchCloseTime * 1000).Wait();//经过一定秒数后关闭PLC的ControlSwitch
            SqlCommand closeSwitchSql = new SqlCommand();
            closeSwitchSql.CommandText = "INSERT INTO R_Command([CommandID],[DeviceID],[ParamName],[ParamValue],[UpdateTime],[UpdateBy],[Runned]) VALUES(@commandid,@deviceid,@paramname,@paramvalue,GETDATE(),@updateby,'0')";
            closeSwitchSql.Parameters.Add(new SqlParameter("@commandid", DBHelper.GetGuid));
            closeSwitchSql.Parameters.Add(new SqlParameter("@deviceid", fcmsId));
            closeSwitchSql.Parameters.Add(new SqlParameter("@paramname", controlSwitch));
            closeSwitchSql.Parameters.Add(new SqlParameter("@paramvalue", "0"));
            closeSwitchSql.Parameters.Add(new SqlParameter("@updateby", Global.UserID));

            dh.RunCommand(closeSwitchSql);

            return count > 0;


        }

        /// <summary>
        /// 将byte列表拼接成16进制字符串
        /// </summary>
        /// <param name="listByte">待拼接的byte列表</param>
        /// <returns>拼接后的16进制字符串</returns>
        private string GetCommandString(List<byte> listByte)
        {
            StringBuilder command = new StringBuilder();
            foreach (byte b in listByte)
            {
                command.AppendFormat("{0:X2}", b);
            }            
            return command.ToString();
        }

        /// <summary>
        /// 获得偏移量的byte列表版本
        /// </summary>
        /// <param name="offset">便宜量数字</param>
        /// <returns>偏移量的byte列表</returns>
        private List<byte> GetOffset(uint offset)
        {
            List<byte> offsetList = new List<byte>();
            switch (offset)
            {
                case 0:
                    {
                        offsetList.Add(0x00);
                        offsetList.Add(0x00);
                        offsetList.Add(0x00);
                        offsetList.Add(0x00);
                    }
                    break;
                case 0x800:
                    {
                        offsetList.Add(0x00);
                        offsetList.Add(0x00);
                        offsetList.Add(0x08);
                        offsetList.Add(0x00);
                    }
                    break;
                case 0x1000:
                    {
                        offsetList.Add(0x00);
                        offsetList.Add(0x00);
                        offsetList.Add(0x10);
                        offsetList.Add(0x00);
                    }
                    break;
                case 0x1800:
                    {
                        offsetList.Add(0x00);
                        offsetList.Add(0x00);
                        offsetList.Add(0x18);
                        offsetList.Add(0x00);
                    }
                    break;
                case 0x2000:
                    {
                        offsetList.Add(0x00);
                        offsetList.Add(0x00);
                        offsetList.Add(0x20);
                        offsetList.Add(0x00);
                    }
                    break;
            }
            return offsetList;
        }

        /// <summary>
        /// 将byte列表按照2048字节进行截取，截取后删除被截取的部分
        /// </summary>
        /// <param name="playList">待截取的byte列表</param>
        /// <param name="playListSegment">被截取的部分</param>
        /// <returns>是否有必要继续截取</returns>
        private bool GetFileSegment(ref List<byte> playList, out List<byte> playListSegment)
        {
            if (playList.Count < 0x800)
            {
                playListSegment = playList;
                return false;
            }
            else
            {
                playListSegment = playList.GetRange(0, 0x800);
                playList.RemoveRange(0, 0x800);
                return true;
            }
        }
        /// <summary>
        /// 给指定指令增加CRC校验
        /// </summary>
        /// <param name="commandBytes">待添加校验的指令</param>
        /// <returns>是否校验成功</returns>
        private bool GetCRC(ref List<byte> commandBytes)
        {
            try
            {
                ushort num = 0;                
                foreach(byte item in commandBytes.GetRange(1,commandBytes.Count-1)) //帧头0x02并不参与CRC校验，所以应从commandBytes的第二位开始
                {
                    num = (ushort)(this.crcTable[((num >> 8) ^ item) & 0xff] ^ (num << 8));
                } 
                List<byte> crcValue = new List<byte>();
                byte[] bytes = BitConverter.GetBytes(num);
                crcValue = bytes.ToList<byte>();
                crcValue.Reverse();
                if (crcValue.Count != 2)
                {
                    return false;
                }
                commandBytes.AddRange(crcValue);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// CRC表
        /// </summary>
        private readonly ushort[] crcTable = new ushort[] 
        {
            0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
            0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
            0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
            0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
            0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
            0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
            0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
            0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
            0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
            0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
            0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
            0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
            0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
            0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
            0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
            0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0
         };

        /// <summary>
        /// 指令字符转义
        /// </summary>
        /// <param name="commandBytes">用以转义的Byte列表</param>
        /// <param name="indextobegin">开始转义的位置</param>
        /// <returns>是否转义成功</returns>
        private bool EscapeString(ref List<byte> commandBytes, int indextobegin)
        {
            try
            {
                int startIndex = indextobegin;
                int index = 0;
                do
                {
                    index = commandBytes.FindIndex(startIndex, x => x == 0x1b);
                    if (index == -1)
                    {
                        break;
                    }
                    startIndex = index + 1;
                    commandBytes[index] = 0x1b;
                    commandBytes.Insert(index + 1, 0);
                }
                while (startIndex < (commandBytes.Count - 1));
                startIndex = indextobegin;
                index = 0;
                do
                {
                    index = commandBytes.FindIndex(startIndex, x => x == 0x02);
                    if (index == -1)
                    {
                        break;
                    }
                    startIndex = index + 1;
                    commandBytes[index] = 0x1b;
                    commandBytes.Insert(index + 1, 0xe7);
                }
                while (startIndex < (commandBytes.Count - 1));
                startIndex = indextobegin;
                index = 0;
                do
                {
                    index = commandBytes.FindIndex(startIndex, x => x == 0x03);
                    if (index == -1)
                    {
                        break;
                    }
                    startIndex = index + 1;
                    commandBytes[index] = 0x1b;
                    commandBytes.Insert(index + 1, 0xe8);
                }
                while (startIndex < (commandBytes.Count - 1));
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
